package dbinit;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.price.model.PriceType;
import core.util.HibernateCoreUtil;

public class InitPriceType
{
	public static PriceType getPriceTypeByName(String name)
	{
		PriceType pt = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Long uuid = 0L;
		try
		{
			transaction = session.beginTransaction();
			 List <PriceType> pts = session.createQuery("from PriceType pt where pt.priceType='"+name+"'").list();
			 if(pts.size() != 0)
			 {
				 Iterator <PriceType> ptsItr =  pts.iterator(); 
				 while(ptsItr.hasNext())
				 {
					 pt = ptsItr.next() ;
					 break ;
				 }
			 }
			 transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		return pt ;
	}
	public static PriceType getPriceTypeByUuid(Long uuid)
	{
		PriceType pt = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				pt = (PriceType) session.get(PriceType.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return pt ;
	}
	public static Long doinit(String priceType)
	{
		PriceType pt = getPriceTypeByName(priceType);
		if(pt == null)
		{
			Transaction transaction = null;
			Session session = HibernateCoreUtil.getSessionFactory().openSession();
			pt = new PriceType();
			pt.setPriceType(priceType);
			try
			{
				transaction = session.beginTransaction();
				session.save(pt);
				transaction.commit();
			}
			catch(HibernateException he)
			{
				he.printStackTrace();
			}
		}
		return pt.getUuid() ;
	}
}
